package svc

import (
	"context"
	"entgo.io/ent/dialect"
	"private-domain-overseas-service/app/task/api/internal/config"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/migrate"

	_ "github.com/go-sql-driver/mysql"
	"github.com/zeromicro/go-zero/core/logx"
)

type ServiceContext struct {
	Config config.Config
	Orm    *ent.Client
}

func NewServiceContext(c config.Config) *ServiceContext {
	orm := initOrm(c)
	return &ServiceContext{
		Config: c,
		Orm:    orm,
	}
}

// initOrm
func initOrm(c config.Config) *ent.Client {
	ops := make([]ent.Option, 0)
	if c.ShowSQL {
		ops = append(ops, ent.Debug())
	}
	client, err := ent.Open(dialect.MySQL, c.DataSource, ops...)
	if err != nil {
		logx.Errorf("ent.Open error: %v", err)
		panic(err)
	}
	if err := client.Schema.Create(context.Background(),
		migrate.WithDropIndex(true),
	); err != nil {
		logx.Errorf("ent.Schema.Create error: %v", err)
		panic(err)
	}

	return client
}
